package com.yufeng.collaboration.consumer;


import com.yufeng.collaboration.config.RabbitMQConfig;
import com.yufeng.collaboration.entity.Document;
import com.yufeng.collaboration.handler.MyWebSocketHandler;
import com.yufeng.collaboration.mapper.DocumentUserMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;



import java.util.List;

@Component
public class DocumentUpdateConsumer {

    private final DocumentUserMapper documentUserMapper;
    private final MyWebSocketHandler webSocketHandler;

    public DocumentUpdateConsumer(DocumentUserMapper documentUserMapper, MyWebSocketHandler webSocketHandler) {
        this.documentUserMapper = documentUserMapper;
        this.webSocketHandler = webSocketHandler;
    }

    @RabbitListener(queues = RabbitMQConfig.QUEUE_NAME)
    public void handleDocumentUpdate(Document document) {
        // 获取与文档关联的用户 ID 列表
        List<Long> userIds = documentUserMapper.selectUserIdsByDocumentId(document.getId());
        for (Long userId : userIds) {
            // 构建文档更新消息
            String message = "Document " + document.getTitle() + " has been updated.";
            // 发送 WebSocket 消息给相关用户
            webSocketHandler.sendMessageToUser(userId, message);
        }
    }
}